package com.lx.commonlib.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.util.Log;


import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.security.acl.Permission;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 错误信息处理器
 *
 * @author YOLANDA;
 */
public class CrashHandler implements Thread.UncaughtExceptionHandler {

    // 系统默认的UncaughtException处理类
    private Thread.UncaughtExceptionHandler mDefaultHandler;
    // CrashHandler实例
    private static CrashHandler INSTANCE;
    // 程序的Context对象
    private Context context;
    // 用来存储设备信息和异常信息
    private HashMap<String, String> infos = new HashMap<String, String>();
    // 用于格式化日期,作为日志文件名的一部分
    @SuppressLint("SimpleDateFormat")
    private SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");

    //日志文件保存路径
    private String logFilePath;

    private CrashHandler() {
    }

    /**
    * 方法说明: 获取实例
    * created by liuxiong on 2019/3/25 14:38
    */
    public static CrashHandler getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new CrashHandler();
        }
        return INSTANCE;
    }

    /**
    * 方法说明:  销毁对象
    * created by liuxiong on 2017/10/21 10:22
    */
    public static void removeInstance(){
        INSTANCE=null;
    }

    /** 初始化 */
    public void init(Context context,String logFilePath) {
        this.context = context;
        this.logFilePath = logFilePath;
        // 获取系统默认的UncaughtException处理器
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        // 设置该CrashHandler为程序的默认处理器
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        if (handleException(ex) ) {
            //已处理，直接退出应用
            AppManager.getInstance().AppExit(true);
            LogUtil.d("----1  AppManager.getInstance().AppExit(true)");
        } else if(mDefaultHandler != null) {
            // 如果用户没有处理则让系统默认的异常处理器来处理
            mDefaultHandler.uncaughtException(thread, ex);
            LogUtil.d("----2 mDefaultHandler.uncaughtException(thread, ex) ");
        }
    }

    /**
     * 自定义错误处理,收集错误信息 发送错误报告等操作均在此完成.
     *
     * @param ex
     * @return true:如果处理了该异常信息;否则返回false
     */
    private boolean handleException(Throwable ex) {
        if (ex == null) {
            return false;
        }
        // 对不起，软件发生故障，即将重启
//        ToastUtil.show(ex.getMessage());
        // 收集设备参数信息
        collectDeviceInfo(context);
        // 保存日志文件
        saveCrashInfo2File(ex);
        return true;
    }


    /**
     * 收集设备参数信息
     *
     * @param ctx
     */
    private void collectDeviceInfo(Context ctx) {
        try {
            PackageManager pm = ctx.getPackageManager();
            PackageInfo pi = pm.getPackageInfo(ctx.getPackageName(), PackageManager.GET_ACTIVITIES);
            if (pi != null) {
                String versionName = pi.versionName == null ? "null" : pi.versionName;
                String versionCode = pi.versionCode + "";
                infos.put("versionName", versionName);
                infos.put("versionCode", versionCode);
                infos.put("systemSDK", String.valueOf(Build.VERSION.SDK_INT));
                infos.put("visibleVersion", Build.VERSION.RELEASE);
            }
        } catch (Exception e) {
        }
        Field[] fields = Build.class.getDeclaredFields();
        for (Field field : fields) {
            try {
                field.setAccessible(true);
                infos.put(field.getName(), field.get(null).toString());
            } catch (Exception e) {
            }
        }
    }

    /**
     * 保存错误信息到文件中
     *
     * @param ex
     * @return 返回文件名称, 便于将文件传送到服务器
     */
    private String saveCrashInfo2File(Throwable ex) {
        StringBuffer sb = new StringBuffer();
        for (Map.Entry<String, String> entry : infos.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            sb.append(key + "=" + value + "\n");
        }

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        //打印异常信息到logcat
        LogUtil.d("---"+result);
        sb.append(result);

        if(canSave()){ //检查权限
            try {
                String time = formatter.format(new Date());
                String fileName = time + ".txt";
                File dir = new File(logFilePath);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                String path = dir.getAbsolutePath();
                // 删除超过10个日志的记录
                File[] fs = getOrderByDate(path);
                delMoreThenFiles(9, fs);

                String crashFilePath = logFilePath+ File.separator + fileName;
                FileOutputStream fos = new FileOutputStream(crashFilePath);
                fos.write(sb.toString().getBytes());
                fos.close();
                return fileName;
            } catch (Exception e) {
            }
        }
        return null;
    }

    /**
     * 按照日期排序文件
     *
     * @param filePath 文件夹路径
     * @return
     */
    public static File[] getOrderByDate(String filePath) {
        File file = new File(filePath);
        File[] fs = file.listFiles();
        Arrays.sort(fs, new Comparator<File>() {
            @Override
            public int compare(File f1, File f2) {
                long diff = f1.lastModified() - f2.lastModified();
                if (diff > 0)
                    return 1;
                else if (diff == 0)
                    return 0;
                else
                    return -1;
            }
        });

        return fs;
    }

    // 删除超过指定数目的文件
    public static void delMoreThenFiles(int icount, File[] fs) {
        if (fs.length - 1 > icount) {
            int ilen = fs.length;
            for (int i = ilen - 1; i > -1; i--) {
                if (icount <= 0) {
                    // 删除
                    fs[i].delete();
                }
                icount--;
            }
        }
    }

    /**
    * 方法说明:  是否可以保存
    * created by liuxiong on 2019/3/25 15:34
    */
    private boolean canSave(){
        if(logFilePath!=null&&logFilePath.contains(context.getPackageName())){ //项目私有目录，不需要权限
            return true;
        }else if(ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) ==
                PackageManager.PERMISSION_GRANTED){
            return true;
        }else{
            return false;
        }
    }

}
